/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package domain.controller.file;

import domain.controller.*;
import domain.controller.file.ControllerFileHelper;
import domain.model.IRegistro;
import domain.model.file.Registro;
import domain.model.ICategoria;
import java.util.Stack;

/**
 *
 * @author Novo usuário
 */
public class RegistroController implements IRegistroController {
    
    private static RegistroController instance = new RegistroController();

    public static RegistroController getInstance() {
        return instance;
    }
    
    public RegistroController() {
    }

    public Stack listRegistros(ICategoria categoria) throws Exception {
        Stack regsIds = categoria.getRegistrosIds();
        Stack regs = new Stack();
        for (int i = 0; i < regsIds.size(); i++) {
            String regId = (String) regsIds.elementAt(i);
            regs.addElement(getRegistro(regId));
        }
        return regs;
    }

    public Stack buscarRegistros(String palavraChave) throws Exception {

        Stack regsIds = ControllerFileHelper.getIntance().getDescFileNames("regDesc.cfg");
        Stack regs = new Stack();
        for (int i = 0; i < regsIds.size(); i++) {
            String regId = (String) regsIds.elementAt(i);
            IRegistro reg = getRegistro(regId);
            if (reg.getNome().toLowerCase().indexOf(palavraChave.toLowerCase()) != -1) {
                regs.addElement(reg);
            }
        }
        System.gc();
        return regs;
    }

    public IRegistro getRegistro(int registroId) throws Exception {
        return getRegistro(String.valueOf(registroId));
    }

    public IRegistro getRegistro(String registroId) throws Exception {

        if (registroId.indexOf(".") == -1) {
            registroId += ".reg";
        }
        String stream = ControllerFileHelper.getIntance().readFile(registroId);
        return new Registro(stream);
    }
}
